import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img

im = img.imread("D:/PythonExce/NewLern/green.jpg")  # 图像读取
print(im.shape)
plt.imshow(im)  # 图像显示
img.imsave("D:/PythonExce/NewLern/save.jpg", im)  # 图像保存
print("--------------------")


# 使用NumPy等模块完成图像灰度化
def imgGray(im):
    '''
    :param im:  原始图像
    :return:   灰度化图像
    '''
    imgarray = np.array(im)
    rows = im.shape[0]
    print(im.shape)  # (1008, 765, 4) 行，列，颜色（RGB及透明度Alpha通道）
    cols = im.shape[1]
    for i in range(rows):
        for j in range(cols):
            imgarray[i, j, :] = (imgarray[i, j, 0] * 0.299 + imgarray[i, j, 1] * 0.587 + imgarray[i, j, 2] * 0.114)
    return imgarray


im = img.imread("D:/PythonExce/NewLern/green.jpg")
im = imgGray(im)
plt.imshow(im)  # plt.imshow对图像进行处理并显示格式，Jupyter中也能显示图像
plt.show()
print("--------------------")


# 图像二值化

def imgThreshold(im, threshold):
    """
    param im: source image
    :param threshold:  0 - 255
    :return: blackwhite image
    """
    imgarray = np.array(im)
    rows = im.shape[0]
    cols = im.shape[1]
    for i in range(rows):
        for j in range(cols):
            gray = (imgarray[i, j, 0] * 0.299 + imgarray[i, j, 1] * 0.578 + imgarray[i, j, 2] * 0.114)
            if gray <= threshold:
                imgarray[i, j, :] = 0
            else:
                imgarray[i, j, :] = 255
    return imgarray


im = img.imread("D:/PythonExce/NewLern/green.jpg")
im = imgThreshold(im, 128)
plt.imshow(im)
plt.show()
